﻿#include "CMyServerApplication.h"
#include <poco/Exception.h>
#include <poco/Format.h>
#include <poco/ConsoleChannel.h>
#include <poco/FileChannel.h>
#include <poco/SplitterChannel.h>
#include <poco/FormattingChannel.h>
#include <poco/PatternFormatter.h>
#include <poco/AutoPtr.h>
#include <poco/Path.h>
#include <poco/File.h>
#include <Poco/Net/ServerSocket.h>
#include <poco/Net/TCPServer.h>
#include "CNewConnectionFactory.h"
#include "CNewConnection.h"
#include <iostream>
#include <fmt/core.h>
#include <toolfunction.h>
#include "CNewConnection.h"
#include <Poco/Net/TCPServerConnectionFactory.h>
#include "MyDalyLog.h"


CMyServerApplication::CMyServerApplication() {

}

CMyServerApplication::~CMyServerApplication() {

}

void CMyServerApplication::initialize(Application& self) {
	std::string configPath = fmt::format("{}Config\\config.ini", config().getString("application.dir"));

	//加载配置文件
	loadConfiguration(configPath);

	//基类系统初始化
	Application::initialize(self);
}

void CMyServerApplication::uninitialize() {
	/**************自定义释放内容*************/
	spdlog::drop_all();		//取消全局注册
	spdlog::shutdown();		//释放日志

	/************释放框架**********/
	Application::uninitialize();
}

void CMyServerApplication::defineOptions(Poco::Util::OptionSet& options) {

}

void CMyServerApplication::handleOption(const std::string& name, const std::string& value) {

}

int CMyServerApplication::main(const std::vector<std::string>& args) {

	std::string msg;
	//获取配置文件中服务端口号
	unsigned short port = (unsigned short)config().getInt("App.Port");

	//创建一个serversocket
	Poco::Net::ServerSocket sock(port);


	//创建一个TCPServer类并将创建好的socketServer传递进来
	
	//方案1
	//Poco::Net::TCPServer srv(new CNewConnectionFactory(), sock);		//OK

	//方案2：TCPServerConnectionFactoryImpl
	//调整套接字参数
	Poco::Net::TCPServerParams::Ptr serverParams(new Poco::Net::TCPServerParams());
	//serverParams->setMaxThreads(2);		//设置最大并发数，超过此数量的连接，不会被拒绝，但是不会调用处理线程
	Poco::Net::TCPServer srv(new Poco::Net::TCPServerConnectionFactoryImpl<CNewConnection>(), sock, serverParams);

	//启动TCPServer
	srv.start();

	Info(fmt::format("TCP服务启动成功，监听端口[{}]", (int)port));

	//等待进程结束
	waitForTerminationRequest();

	//关闭tcpserver
	srv.stop();

	Info("***************程序关闭成功**************");

	return Application::EXIT_OK;
}
